package com.learnrn;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;

import com.facebook.react.bridge.ActivityEventListener;
import com.facebook.react.bridge.BaseActivityEventListener;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.modules.core.DeviceEventManagerModule;

import static android.app.Activity.RESULT_OK;

/**
 * Created by thinkpad on 2017/9/28.
 */

public class ExampleInterface extends ReactContextBaseJavaModule implements ActivityEventListener {
    ReactApplicationContext aContext;
    Promise interfacePromise; //定义成员变量，保存将收到的Promise变量 4-2-11

//    private final ActivityEventListener mActivityEventListener = new BaseActivityEventListener() {
//
//        public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
//            if (requestCode != 1 || resultCode != RESULT_OK) return;
//            Uri contactData = data.getData();
//            Cursor cursor = aContext.getContentResolver().query(contactData, null, null, null, null);
////            Cursor cursor = activity.managedQuery(contactData, null, null, null, null);
//            cursor.moveToFirst();
//            String toRNMessage = getContactInfo(cursor);//取得结果字符串
////            sendMessage(toRNMessage);//接口发送 4-2-8
//            if (toRNMessage != null) {
//                interfacePromise.resolve(toRNMessage);//Promise发送
//            }
//        }
//
//    };

    public ExampleInterface(ReactApplicationContext reactContext) {
        super(reactContext);
        aContext = reactContext;//保存MainActivity 传来的上下文实例
        reactContext.addActivityEventListener(this);
    }

    @Override
    public String getName() {
        return "ExampleInterface";
    }

    @ReactMethod
    public void HandleMessage(String aMessage, Promise aPromise) {
        interfacePromise = aPromise;
        //处理原生代码处理消息的函数
        Log.i("RNMessage", "received message from RN:" + aMessage);
//        Intent aIntent = new Intent(aContext, Main2Activity.class);
//        aIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        aContext.startActivity(aIntent);//切换到Main2Activity
        Intent aIntent = new Intent(Intent.ACTION_PICK);
        aIntent.setType(ContactsContract.Contacts.CONTENT_TYPE);
        Bundle b = new Bundle();
        aContext.startActivityForResult(aIntent, 1, b);//调用系统提供的选择联系人界面
    }

    public void sendMessage(String aMessage) {
        aContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit("AndroidToRNMessage", aMessage);
    }

    //取出用户选择的联系人的姓名与电话号码，按某规则生成结果字符串
    private String getContactInfo(Cursor cursor) {
        try {
            String name = "";
            String phoneNumber = "";
            int idColumn = cursor.getColumnIndex(ContactsContract.Contacts._ID);
            String contactId = cursor.getString(idColumn);
            String queryString = ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + contactId;
            Uri aUri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
            Cursor phone = aContext.getContentResolver().query(aUri, null, queryString, null, null);
            String dn = ContactsContract.Contacts.DISPLAY_NAME;
            String pn = ContactsContract.CommonDataKinds.Phone.NUMBER;
            if (phone.moveToFirst()) {
                for (; !phone.isAfterLast(); phone.moveToNext()) {
                    dn = name = cursor.getString(cursor.getColumnIndex(dn));
                    phoneNumber = phone.getString(phone.getColumnIndex(pn));
                }
                phone.close();
            }
            String result = "{\"msgType\":\"pickContactResult\", \"dispalyName\":\"" + name + "\", \"peerNumber\":\"" + phoneNumber + "\"}";
            return result;
        } catch (Exception e) {
            interfacePromise.reject("error while get contact", e);
        }
        return null;
    }

    @Override
    public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
        if (requestCode != 1 || resultCode != RESULT_OK) return;
        Uri contactData = data.getData();
        Cursor cursor = aContext.getContentResolver().query(contactData, null, null, null, null);
//            Cursor cursor = activity.managedQuery(contactData, null, null, null, null);
        cursor.moveToFirst();
        String toRNMessage = getContactInfo(cursor);//取得结果字符串
//            sendMessage(toRNMessage);//接口发送 4-2-8
        if (toRNMessage != null) {
            interfacePromise.resolve(toRNMessage);//Promise发送
        }
    }

    @Override
    public void onNewIntent(Intent intent) {

    }
}
